package com.shanghaionstar.discover.geofence.presenter;

import android.content.Intent;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.MyPost;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.mag.GeofenceInfoEntity;
import com.shanghaionstar.R;
import com.shanghaionstar.discover.geofence.GeofenceHomeActivity;
import com.shanghaionstar.discover.geofence.GeofenceInfoActivity;
import com.shanghaionstar.discover.geofence.GeofencePreviewActivity;
import com.shanghaionstar.discover.geofence.iview.IGeofenceDeatilView;
import com.shanghaionstar.discover.geofence.service.GeofenceService;
import com.shanghaionstar.enumtype.AlertType;
import com.shanghaionstar.utils.AlertDialogUtil;

import java.util.List;

import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by 7828wc on 16/7/21.
 */
public class GeofenceDetailPresenter extends BasePresenter<Object> {
    private GeofenceService service;
    private IGeofenceDeatilView view;
//    private boolean isInitData = false;
//    private boolean isCheckSwitchOpen = false;
    private GeofenceInfoEntity detailGeoFenceInfo;
    private BaseActivity mContext;

    public GeofenceDetailPresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    @Override
    public void setView(IMVPView<Object> view) {
        super.setView(view);
        service = new GeofenceService(view.onActivity());
        this.view = (IGeofenceDeatilView) view;
        mContext = (BaseActivity) view.onActivity();
    }

    public void getIntent() {
        detailGeoFenceInfo = (GeofenceInfoEntity) mContext.getIntent().getSerializableExtra(GeofenceInfoEntity.GEOFENCE_TAG);
    }

    public void initData() {
        if (detailGeoFenceInfo == null) mContext.finish();
//        isInitData = true;
        view.initData(detailGeoFenceInfo);
//        isInitData = false;
    }

    public void onCheck(boolean isChecked) {
//        if (isInitData) return;
//        isCheckSwitchOpen = true;
        if (isChecked) {
            detailGeoFenceInfo.setGeoFencingStatus(AlertType.ON.value());
        } else {
            detailGeoFenceInfo.setGeoFencingStatus(AlertType.OFF.value());
        }
//        geofenceUtil.processGeoFencing(detailGeoFenceInfo, Constants.OPERATE_TYPE_UPDATE);
        detailGeoFenceInfo.setOperationType(Constants.OPERATE_TYPE_UPDATE);
        updateGeofencing(detailGeoFenceInfo);
//        BusinessUtil.sendReportByClickType(view.onActivity(), FunctionNameFindId.Security_Zone_Switch.getStringValue());
    }

    public void deleteGeofencing() {
        detailGeoFenceInfo.setOperationType(Constants.OPERATE_TYPE_DELETE);
        deleteGeofencing(detailGeoFenceInfo);
    }

    public void setRule(GeofenceInfoEntity entity){
        if (!CommonUtil.isNull(entity.getAlertType())) {
            if (entity.getAlertType().equals(AlertType.Out.value())) {
                entity.setRule(view.onActivity().getString(R.string.out_geofence));
            } else {
                entity.setRule(view.onActivity().getString(R.string.in_geofence));
            }
        } else {
            entity.setRule(AlertType.All.name());
        }
    }


    public String getRangeUnit(GeofenceInfoEntity entity){
        return entity.getRangeUnit().equalsIgnoreCase("KM")?mContext.getString(R.string.geofence_range_unit_km):mContext.getString(R.string.geofence_range_unit_m);
    }


    private void deleteGeofencing(final GeofenceInfoEntity entity) {
        view.setLoading(true);
        subscription = service.init().flatMap(new Func1<String, Observable<String>>() {
            @Override
            public Observable<String> call(String str) {
                return service.processGeofencing(entity);
            }
        }).subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<String>() {
                    @Override
                    public void call(String geofenceList) {
                        view.onReponseSuccess(null);
                        view.setLoading(false);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //抛出Error异常
                        view.onResponseError((OnStarException) throwable);
                        view.setLoading(false);
                    }
                });

    }

    public void getGeoFencings() {
        view.setLoading(true);
        subscription = service.init().flatMap(new Func1<String, Observable<List<GeofenceInfoEntity>>>() {
            @Override
            public Observable<List<GeofenceInfoEntity>> call(String entity) {
                return service.getGeofencing();
            }
        }).subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<List<GeofenceInfoEntity>>() {
                    @Override
                    public void call(List<GeofenceInfoEntity> geofenceList) {
                        if (geofenceList != null && geofenceList.size() > 0) {
                            detailGeoFenceInfo = geofenceList.get(0);
                            view.onReponseSuccess(geofenceList.get(0));
                        } else {
                            view.onReponseSuccess(new GeofenceInfoEntity());
                        }
                        view.setLoading(false);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //抛出Error异常
                        view.onResponseError((OnStarException) throwable);
                        view.setLoading(false);
                    }
                });

    }

    public void onFailed(){
//        if(isCheckSwitchOpen){
//            isInitData=true;
            if(!CommonUtil.isNull(detailGeoFenceInfo.getGeoFencingStatus())&&detailGeoFenceInfo.getGeoFencingStatus().equalsIgnoreCase(AlertType.ON.value())) {
                view.onFailed(false);
                detailGeoFenceInfo.setGeoFencingStatus(AlertType.OFF.value());
            }else{
                view.onFailed(true);
                detailGeoFenceInfo.setGeoFencingStatus(AlertType.ON.value());
            }
//            isCheckSwitchOpen=false;
//            isInitData=false;
//        }
    }

//    private Handler resultHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case Constants.SHOW_GEOFENCE_DETAIL:
//                    detailGeoFenceInfo = (GeoFenceInfo) msg.getData().getSerializable(GeoFenceInfo.GEOFENCE_TAG);
//                    initDatas();
//                    showProgressLayout(false);
//                    break;
//                case Constants.ERROR:
//                    ErrorInfo errorInfo1 = (ErrorInfo) msg.getData().getSerializable("errorInfo");
//                    if (errorInfo1 != null) {
//                        ErrorCodeUtil.ShowErrorSompMsg(GeofenceDetailActivity.this, errorInfo1);
//                    }
//                    showProgressLayout(false);
//                    if(isCheckSwitchOpen){
//                        isInitData=true;
//                        if(!CommonUtil.isNull(detailGeoFenceInfo.getGeoFencingStatus())&&detailGeoFenceInfo.getGeoFencingStatus().equalsIgnoreCase(AlertType.ON.value())) {
//                            switch_open.setChecked(false);
//                            detailGeoFenceInfo.setGeoFencingStatus(AlertType.OFF.value());
//                        }else{
//                            switch_open.setChecked(true);
//                            detailGeoFenceInfo.setGeoFencingStatus(AlertType.ON.value());
//                        }
//                        isCheckSwitchOpen=false;
//                        isInitData=false;
//                    }
//                    break;
//                case Constants.SHOW_GEOFENCE_DELETE:
//                    //电子围栏删除成功后，需跳转到添加电子围栏页面
//                    Intent intent = new Intent(GeofenceDetailActivity.this, GeoFenceAddActivity.class);
//                    intent.putExtra("isAdd", true);
//                    startActivity(intent);
//                    finish();
//                    break;
//                default:
//                    break;
//            }
//        }
//    };

//    if (CommonUtil.isNull(json)) {
//        if (Constants.OPERATE_TYPE_DELETE.equalsIgnoreCase(operateType)) {
//            msg.what = Constants.SHOW_GEOFENCE_DELETE;
//            resultHandler.sendMessage(msg);
//        }else{
//            MyPost.post(new Runnable() {
//                @Override
//                public void run() {
//                    AlertDialogUtil.showAlertDialog(context,R.string.dialog_warning,R.string.poi_not_city_str);
//                }
//            });
//            resultHandler.sendEmptyMessage(Constants.ERROR);
//        }
//    } else {
//        getGeoFencings();
//    }

    public void updateGeofencing(final GeofenceInfoEntity entity) {
        view.setLoading(true);
        subscription = service.init().flatMap(new Func1<String, Observable<String>>() {
            @Override
            public Observable<String> call(String str) {
                return service.processGeofencing(entity);
            }
        }).subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<String>() {
                    @Override
                    public void call(String geofenceList) {
                        if (CommonUtil.isNull(geofenceList)) {
                            MyPost.post(new Runnable() {
                                @Override
                                public void run() {
                                    AlertDialogUtil.showAlertDialog(mContext, R.string.dialog_warning, R.string.poi_not_city_str);
                                }
                            });
//                            view.onResponseError(null);
                        } else {
                            getGeoFencings();
                        }
//                        view.onReponseSuccess(null);
                        view.setLoading(false);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //抛出Error异常
                        view.onResponseError((OnStarException) throwable);
                        view.setLoading(false);
                    }
                });

    }

    public void launchUpdate() {
//        BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.Update_Button.getStringValue());
        Intent intent = new Intent(mContext, GeofenceInfoActivity.class);
        intent.putExtra("isUpdate", true);
        intent.putExtra(GeofenceInfoEntity.GEOFENCE_TAG, detailGeoFenceInfo);
        mContext.startActivity(intent);
//        mContext.finish();
    }

    public void launchPreview() {
//        BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.View_On_Map.getStringValue());
        Intent intent = new Intent(mContext, GeofencePreviewActivity.class);
        intent.putExtra(GeofenceInfoEntity.GEOFENCE_TAG, detailGeoFenceInfo);
        mContext.startActivity(intent);
    }

    public void launchHome() {
        Intent intent = new Intent(mContext, GeofenceHomeActivity.class);
        mContext.startActivity(intent);
        mContext.finish();
    }


}
